/**
 * url : url
 * data : 参数
 * method : get，post
 * callback : 回掉函数
 */
function http(url, data, method, callback) { 
  wx.getNetworkType({
    success: function (res) {
      // 返回网络类型, 有效值：
      // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
      var networkType = res.networkType
      if (networkType == "none") {
        wx.showToast({
          title: '网络请求失败',
          icon: 'loading',
          duration: 2000
        });
      } else {
        wx.request({
          url: url,
          data: data,
          header: { 'Content-Type': 'application/json' },
          method: method,
          success: function (res) {
            callback(res.data);
          },
          fail: function () {
            callback(null);
          },
          complete: function () {

          }
        })
      }
    }
  })
}

/**
 * 处理查询信息中的过滤字段（转数组）
 */
function filterToArr(filter) {
  var content = [];
  if (filter && filter.length > 0) {
    var values = filter.split(';');
    for (var item in values) {
      var vals = values[item].lastIndexOf('_');
      content.push({
        key: values[item].substr(0, vals),
        value: values[item].substr(vals + 1)
      })
    }
  }
  return content;
}
/**
 * 处理查询信息中的过滤字段（转字符串）
 */
function filterToStr(filter) {
  var content = "";
  if (filter && filter.length > 0) {
    for (var item in filter) {
      if (filter[item].key && filter[item].value) {
        content += filter[item].key + "_" + filter[item].value + ";";
      }
    }
  }
  return content.substr(0, content.length - 1);
}

module.exports = {
  http: http,
  filterToArr: filterToArr,
  filterToStr: filterToStr
}